﻿using System;
using System.Collections.Generic;
using System.IO;
using Autodesk.Revit.DB;

namespace YJKStairs.CommonUnit
{
	public class FamilyLoadUtils
	{
		public static bool LoadFamily(Autodesk.Revit.DB.Document doc, string strFamliyPath, string strFamilyName, string strSymbolName, out Family outFam)
		{
			bool result = false;
			outFam = null;
			if (!File.Exists(strFamliyPath))
			{
				return result;
			}
			List<Family> list = new List<Family>();
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(doc);
			filteredElementCollector.OfClass(typeof(Family));
			foreach (Element element in filteredElementCollector)
			{
				Family family = (Family)element;
				if (family.Name.Contains(strFamilyName))
				{
					list.Add(family);
				}
			}
			bool flag = FamilyLoadUtils.HasLoadFamily(doc, strSymbolName, ref outFam, list);
			if (flag)
			{
				result = true;
			}
			else if (!flag && list.Count == 0)
			{
				result = doc.LoadFamily(strFamliyPath, out outFam);
			}
			else if (!flag && list.Count > 0)
			{
				string text = Path.GetDirectoryName(strFamliyPath) + "\\" + strFamilyName + "-1.rfa";
				File.Copy(strFamliyPath, text, true);
				if (File.Exists(text))
				{
					try
					{
                        result = doc.LoadFamily(text, out outFam);
						File.Delete(text);
					}
					catch (Exception)
					{
						File.Delete(text);
					}
				}
			}
			return result;
		}

		private static bool HasLoadFamily(Autodesk.Revit.DB.Document doc, string strSymbolName, ref Family outFam, List<Family> lstExistFam)
		{
			bool result = false;
			foreach (Family family in lstExistFam)
			{
				IEnumerable<ElementId> familySymbolIds = family.GetFamilySymbolIds();
				List<string> list = new List<string>();
				foreach (ElementId elementId in familySymbolIds)
				{
					FamilySymbol familySymbol = doc.GetElement(elementId) as FamilySymbol;
					if (familySymbol != null)
					{
						list.Add(familySymbol.Name);
					}
				}
				if (list.Contains(strSymbolName))
				{
					outFam = family;
					result = true;
					break;
				}
			}
			return result;
		}
	}
}
